package nbcp.web.open

import ch.qos.logback.classic.Logger
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import nbcp.base.comm.*
import nbcp.base.extend.*
import nbcp.base.utils.CodeUtil
import nbcp.base.utils.HttpUtil

import nbcp.base.utils.MyUtil
import nbcp.base.utils.SpringUtil
import nbcp.comm.JsonpMapping
import nbcp.db.CodeName
import nbcp.db.IntCodeName
import nbcp.db.mongo.entity.SysUser
import nbcp.db.mongo.mor
import nbcp.db.sys.doLogin
import nbcp.model.IdUrlMsg

import nbcp.service.srv
import nbcp.web.WriteJsonRawValue
import org.springframework.beans.factory.annotation.Autowired
import springfox.documentation.annotations.ApiIgnore
import java.io.File
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession
import nbcp.interfaces.DemoService
import org.apache.dubbo.config.annotation.Reference


/**
 * Created by udi on 17-3-19.
 */

@ApiIgnore
@OpenAction
@RestController
@JsonpMapping("/open")
class Open_Controller {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }


    @GetMapping("/hi")
    fun hi(session: HttpSession): String {
        return session.getAttribute("II").AsString();
    }

    @Reference
    private lateinit var demoService: DemoService

    @GetMapping("/hi2")
    fun hi2(session: HttpSession): ApiResult<IdUrlMsg> {
        return ApiResult.of(IdUrlMsg("abc", demoService.sayHello("OK")));
    }

    @Value("\${spring.application.name}")
    var applicationName: String = "";

    @GetMapping("/log")
    fun log(filter: List<String>?, not: List<String>?, tail: Boolean?,
            extCount: Int = 0, matchLines: Int, help: Boolean?,
            f:List<String>?,c:Int=0,n:Int=0,
            request: HttpServletRequest): String {

        var logFile = (logger as Logger).getLoggerFile("FILE-OUT");


        var log_text = File(logFile).FilterLines(
                n.AsInt( matchLines),
                c.AsInt(extCount),
                f?:filter ?: emptyList(),
                not ?: emptyList(),
                tail
                        ?: true).joinToString("\n")

        var help_html = "";
        if( help == true){
            help_html = """<pre>
    日志参数,优先使用简写参数：
        filter:f  表示过滤匹配条件，可以多个
        not:      表示过滤匹配不满足条件的行，可以多个
        tail:     表示是否从最底部显示，默认是 true
        extCount:c 表示如果有 filter , not 的话，返回匹配行的前后多少行。
        matchLines:n 表示返回的总行数
</pre>
<hr />"""
        }

        return """<!DOCTYPE html>
<html>
<head><title>${applicationName} - 日志</title></head>
<body>${help_html}<pre>${log_text}</pre></body>
</html>
"""
    }


    data class cn_cityModel(var c: Int, var n: String)


    @GetMapping("/getCity")
    fun getCity(ip: String): ApiResult<IntCodeName> {
        if (ip.isEmpty()) {
            return ApiResult("ip不能为空");
        }
        if (MyUtil.isLocalIp(ip)) {
            return ApiResult("不能是本机Ip");
        }
        var serverUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
        var http = HttpUtil(serverUrl);
        var res = http.doGet();

        if (http.status != 200) {
            return ApiResult(http.msg.AsString("获取城市信息出错"))
        }
        var resJson = res.FromJson<JsonMap>();
        if (resJson["code"].toString().toInt() != 0) {
            return ApiResult(http.msg.AsString("获取城市信息数据出错"))
        }

//        if( (resJson["data"] is HashMap<*,*> ) == false){
//            return CodeName();
//        }
        var data = resJson["data"] as Map<String, *>;

        var county_code = data["county_id"].toString()
        if (county_code.IsNumberic()) {
            return ApiResult.of(IntCodeName(county_code.AsInt(), data["county"].toString()))
        }

        var city_code = data["city_id"].toString()
        if (city_code.IsNumberic()) {
            return ApiResult.of(IntCodeName(city_code.AsInt(), data["city"].toString()))
        }
        var region_code = data["region_id"].toString()
        if (region_code.IsNumberic()) {
            return ApiResult.of(IntCodeName(region_code.AsInt(), data["region"].toString()))
        }

        return ApiResult("获取城市信息数据内容无法识别");
    }
}